package com.mainbo.modular.system.service.impl;

import com.mainbo.core.util.FileUtil;
import com.mainbo.core.util.WebUtils;
import com.mainbo.modular.system.model.PtResources;
import com.mainbo.modular.system.dao.PtResourcesMapper;
import com.mainbo.modular.system.service.IPtResourcesService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mainbo.modular.system.service.StorageService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

import static com.mainbo.core.util.FileUtil.getFileExt;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author moshang
 * @since 2020-02-24
 */
@Service
public class PtResourcesServiceImpl extends ServiceImpl<PtResourcesMapper, PtResources> implements IPtResourcesService {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private PtResourcesMapper ptResourcesMapper;
    @Resource
    private StorageService storageservice;
    @Value("${uploadBasePath:static/upload}")
    private String uploadBasePath;


    @Override
    public PtResources saveWebResources(MultipartFile myfile, String relativePath) {
        String id = UUID.randomUUID().toString();
        String ext = FileUtil.getFileExt(myfile.getOriginalFilename());
        String aimUrl = new StringBuilder(uploadBasePath).append(File.separator)
                .append(relativePath).append(File.separator).append(id).append(".")
                .append(ext).toString();
        if (saveToWeb(myfile, aimUrl)) {
            PtResources resources = new PtResources();
            resources.setId(id);
            resources.setPath(aimUrl.replace("\\", "/"));
            // 部分浏览器web路径只支持 '/'
            resources.setName(FileUtil.getFileName(myfile.getOriginalFilename()));// 文件名，不含扩展名
            resources.setExt(ext); // 扩展名不含.
            resources.setSize(myfile.getSize());
            resources.setDeviceName(FileUtil.WEB_DEVICE_NAME);
            resources.setDeviceId(FileUtil.WEB_DEVICE_ID);
            resources.setState(PtResources.S_TEMP);
            resources.setCrtDttm(new Date());
             ptResourcesMapper.insert(resources);
            return resources;
        }
        return null;
    }

    @Override
    public PtResources saveTmptResources(MultipartFile myfile, String relativePath) {
        try {
            return saveResources(myfile.getInputStream(),
                    myfile.getOriginalFilename(), myfile.getSize(), relativePath,
                    PtResources.S_TEMP);
        } catch (IOException e) {
            logger.error("cann't get fileinputStream", e);
        }
        return null;
    }

    @Override
    public boolean deleteResources(String resId) {
        PtResources resources = null;
        if (StringUtils.isNotEmpty(resId)) {
            resources = ptResourcesMapper.selectById(resId);
            if (resources != null) {
                if (PtResources.S_TEMP != resources.getState()) {
                    PtResources rs = new PtResources();
                    rs.setState(PtResources.S_TEMP);
                    rs.setId(resId);
                    ptResourcesMapper.updateAllColumnById(rs);
                } else {
                    ptResourcesMapper.deleteById(resId);
                    if (FileUtil.WEB_DEVICE_ID.equals(resources.getDeviceId())) {
                        deleteWebFile(resources.getPath());
                    } else {
                        storageservice.delete(resources.getPath());
                    }
                }
                return true;
            }
        }
        return false;
    }

    @Override
    public PtResources updateTmptResources(String oldResId) {
        PtResources resources = ptResourcesMapper.selectById(oldResId);
        if (resources != null && PtResources.S_TEMP == resources.getState()) {
            PtResources newResources = new PtResources();
            newResources.setId(resources.getId());
            newResources.setState(PtResources.S_NORMAL);
            resources.setState(PtResources.S_NORMAL);
            ptResourcesMapper.updateById(newResources);
        }
        return resources;
    }

    protected void deleteWebFile(String path) {
        if (StringUtils.isNotEmpty(path)) {
            File aimFile = new File(WebUtils.getRootPath(), path);
            if (aimFile.exists() && aimFile.isFile()) {
                aimFile.delete();
            }
        }
    }
    protected PtResources saveResources(InputStream stream, String fileName,
                                      Long fileSize, String relativePath, int fileState) {

        String id = UUID.randomUUID().toString();
        String ext = getFileExt(fileName);
        String aimUrl = new StringBuilder(nullToEmpty(relativePath))
                .append(File.separator).append(id).append(".").append(ext).toString();

        String filePath = storageservice.upload(stream, fileName, aimUrl);

        PtResources resources = new PtResources();
        resources.setId(id);
        resources.setPath(filePath);
        resources.setName(FileUtil.getFileName(fileName));// 文件名，不含扩展名
        resources.setExt(ext); // 扩展名不含.
        resources.setSize(fileSize);
        resources.setDeviceName(storageservice.parseDevice(filePath));
        resources.setState(fileState);
        resources.setCrtDttm(new Date());
        ptResourcesMapper.insert(resources);

        return resources;
    }

    public static String nullToEmpty(Object o) {
        return o == null ? "" : o.toString();
    }
    protected boolean saveToWeb(MultipartFile myfile, String aimUrl) {
        try {
            if (StringUtils.isBlank(aimUrl)) {
                throw new IllegalStateException("aimUrl cann't be null!");
            }
            File aimFile = new File(WebUtils.getRootPath(), aimUrl);
            File parentFolder = aimFile.getParentFile();
            if (parentFolder != null && !parentFolder.exists()) {
                parentFolder.mkdirs();
            }
           FileUtils.copyInputStreamToFile(myfile.getInputStream(), aimFile);
            logger.info(">> [save success ] " + aimUrl);
        } catch (Exception e) {
            logger.error("upload error ", e);
            return false;
        }
        return true;
    }

}
